<?php

namespace App\Helpers;

use App\Models\SystemLog;
use Illuminate\Support\Facades\Auth;

trait ContractApiTrait
{

    //
    public function getRequestData($name,$data):array
    {
        $businessData=$this->getBusinessData($name,$data);
        $businessData['sign']=$this->getBusinessDataSign($businessData);
        return $businessData;
    }
    //
    public function getBusinessData($name,$data):array
    {
        return [
            "name"=>$name,
            "version"=>"",
            "app_key"=>$this->getKey(),
            "data"=>$this->getDataString($data),
            "timestamp"=>date('Y-m-d H:i:s'),
            "format"=>"json",
        ];
    }
    public function getDataString($data):string
    {
        return urlencode(json_encode($data));
    }

    //
    public function getBusinessDataSign($businessData):string
    {
        ksort($businessData);
        $sortStr='';
        $secret=$this->getSecret();
        foreach ($businessData as $key=>$value){
            $sortStr.=$key;
            $sortStr.=$value;
        }
        return strtoupper(md5($secret.$sortStr.$secret));
    }

    //
    public function getKey():string
    {
        return '1358752943834136576';
    }
    //
    public function getSecret():string
    {
        return '35c8b11fff604cf1854a875a0f4e0615';
    }

    //
    public function getAgent($org='3059176200',$operator='7e3b08fa-3069-4d95-9bb9-84bef1920b15'):array
    {
        return [
            'organizationOpenId'=>$org,
            'operator'=>[
                'openId'=>$operator,
            ],
        ];
    }

    //
    public function getTemplateId():string
    {
        return 'yDCDxUUndn7miqUJE1yYEGB0yQNH4OBw';
    }
    //
    public function getQizongApiUrl():string
    {
        return 'https://openapi.qizongyun.com';
    }

    //
    public function createContractErrorLog($type,$resData,$request)
    {
        SystemLog::create([
            'type'=>$type,
            'info'=>$resData['msg'],
            'param'=>json_encode($request->all()),
            'extra'=>$request->user()->id??'',
        ]);
    }

}
